package com.cbnu.SmartCampusLife;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.http.AccessToken;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class SNS extends Activity {
    
	private static final String TAG = "MainActivity";
	
	EditText st;
	EditText resultList;
	Twitter twitter;
	ArrayList<HashMap<String, String>> list;
	ListView listView;
	
	String stu_name;
	
	View.OnClickListener bHandler = new View.OnClickListener() {
		
		public void onClick(View v) {
			switch(v.getId()){
			case R.id.send :
				updateStatus();
				getTimeLine();
				break; 
			case R.id.receive:
				getTimeLine();
				break;
			}
			
		}
	};

	@SuppressWarnings("unused")
	void updateStatus(){
		twitter = getTwitter();
		Status status = null;
		try {
			FileInputStream fis = openFileInput("stu_name.txt");
        	BufferedInputStream bis = new BufferedInputStream(fis);
    		BufferedReader dis = new BufferedReader(new InputStreamReader(bis));
			stu_name = dis.readLine();
		} catch(Exception e) {;}
		try {
			Calendar now = Calendar.getInstance();
			int year = now.get(Calendar.YEAR);
			int month = now.get(Calendar.MONTH) + 1;
			int day = now.get(Calendar.DAY_OF_MONTH);
			status = twitter.updateStatus(stu_name + " : " + st.getText().toString() + " $ " + year + "/" + month + "/" + day);
			Toast.makeText(this, "전송 완료", Toast.LENGTH_SHORT).show();
			getTimeLine();
		} catch (TwitterException e) {
			Log.v(TAG, "Update Error");
		}
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(st.getWindowToken(), 0);
		imm.hideSoftInputFromWindow(resultList.getWindowToken(), 0);
		getTimeLine();
	}
	
	private Twitter getTwitter(){
		twitter = new TwitterFactory().getInstance();
		twitter.setOAuthConsumer("43CdpWZ56QUiqKEDFy3hg", "y1BbrgIlIZsGqP1AiFAYoubcy2FgcmUkglE7f2wxNo");
		AccessToken token = new AccessToken("546628339-avbheNkY0JqS0ffOrUGTsiz1F7ExBYip2SdTHw6o", "z5uA850zAR4ji3OBaGGljY0hWCkNYBKc76ePy23SVrc");
		twitter.setOAuthAccessToken(token);
		return twitter;
		
	}
	
	void getTimeLine(){
		twitter = getTwitter();
		list = new ArrayList<HashMap<String, String>>();
		List<Status> timeLine;
		StringBuffer sb = new StringBuffer();
		try{
			timeLine = twitter.getHomeTimeline(); // 만약 타임라인이 나오지 않는다면 getFriendsTimeline()으로 바꿀 것
			for(Status status : timeLine) {
				sb.append(status.getText() + " \n");
				sb.append("\n\n");
				Log.d("sb", sb.toString());
				resultList.setText(sb.toString());
				int length = sb.length();
				
				int t = 0, tt = 0;
				t = sb.indexOf(" : ");
				tt = sb.indexOf(" $ ");
				String name = sb.substring(0, t);
				String content = sb.substring(t + 3, tt);
				String date = sb.substring(tt + 3);
				HashMap<String, String> map = new HashMap<String, String>();
		        map.put("name", name);
		        map.put("content", content);
		        map.put("date", date);
		        list.add(map);
		        
		        SimpleAdapter sa = new SimpleAdapter(this, list, R.layout.twitcontent, new String[] {"name", "content", "date"}, new int[] {R.id.tw_name, R.id.tw_content, R.id.tw_date});
		        listView.setAdapter(sa);
				sb.delete(0, length);
			}
		} catch(Exception e) {
			Log.v(TAG, "timeline error");
		}
		
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(st.getWindowToken(), 0);
		imm.hideSoftInputFromWindow(resultList.getWindowToken(), 0);
	}

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.twitmain);
       
        st = (EditText)findViewById(R.id.status);
        resultList = (EditText)findViewById(R.id.listresult);
        listView = (ListView)findViewById(R.id.sns_listView);
        
        getTimeLine();
        findViewById(R.id.send).setOnClickListener(bHandler);
        findViewById(R.id.receive).setOnClickListener(bHandler);
        
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(st.getWindowToken(), 0);
        imm.hideSoftInputFromWindow(resultList.getWindowToken(), 0);
	}
}